package hn.cch.spring.core.bootstrap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;

import java.lang.reflect.Field;
import java.util.Locale;

@SpringBootApplication
public class BootStrapApplication {

    private static final Logger logger = LoggerFactory.getLogger(BootStrapApplication.class);


    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(BootStrapApplication.class, args);
        try {
            Field field = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
            field.setAccessible(true);
            ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
            // Object object = field.get(beanFactory);
            // if (object instanceof Map<?, ?>) {
            //     Map<String, Object> map = (Map<String, Object>)object;
            //     map.forEach((key, value) -> logger.info("{}->{}", key, value));
            // }


            // 国际化：message-en.properties，message-zh.properties
            String english = applicationContext.getMessage("hi", null, Locale.ENGLISH);
            String chinese = applicationContext.getMessage("hi", null, Locale.CHINESE);

            // 获取资源
            Resource[] resources = applicationContext.getResources("classpath*:META-INF/spring.factories");
            for (Resource resource : resources) {
                logger.info(resource.toString());
            }

            // 获取环境配置
            String javaHome = applicationContext.getEnvironment().getProperty("java_home");
            String serverPort = applicationContext.getEnvironment().getProperty("server.port");

            // 发布事件与监听
            applicationContext.publishEvent(new ApplicationEventImpl(applicationContext));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
